IF EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID('PaintImport') AND sysstat & 0xf = 4)
    DROP PROCEDURE [PaintImport]
GO
CREATE PROCEDURE [PaintImport]
(
    @PaintingId int = null output,
    @Title nvarchar(100),
    @PaintingNumber nvarchar(100),
    @Tags nvarchar(max),
    @Authorships nvarchar(max),
    @Subjects nvarchar(max),
    @HandEnable bit,
    @PrinterEnable bit,
    @Frames int
)
AS
BEGIN
	SET NOCOUNT ON
	SELECT @PaintingId=painting_id
	from Painting 
	where painting_number=@PaintingNumber
	
	if(@PaintingId is null)
	begin
	INSERT INTO [painting](
        [title],
        [painting_number],
        [tags],
        [authorships],
        [subjects],
        [hand_enable],
        [printer_enable],
        [frames]
	)
	VALUES(
        @Title,
        @PaintingNumber,
        @Tags,
        @Authorships,
        @Subjects,
        @HandEnable,
        @PrinterEnable,
        @Frames
	)
	SELECT @PaintingId = SCOPE_IDENTITY()
	End
	else
	begin
	UPDATE [painting]
	SET
        [title]=@Title,
        [painting_number]=@PaintingNumber,
        [tags]=@Tags,
        [authorships]=@Authorships,
        [subjects]=@Subjects,
        [update_date]=GetDate(),
        [hand_enable]=@HandEnable,
        [printer_enable]=@PrinterEnable,
        [frames]=@Frames
	WHERE
		[painting_id] = @PaintingId
	end
	
	exec PaintAuthorshipBatchUpdate @PaintingId=@PaintingId,@Authorships=@Authorships
	exec PaintSubjectBatchUpdate @PaintingId=@PaintingId,@Subjects=@Subjects
	exec PaintTagBatchUpdate @PaintingId=@PaintingId,@Tags=@Tags
		
END
GO
